<?php


namespace app\index\controller;


use app\common\controller\CommonController;
use app\common\enum\MainEnum;
use app\common\service\RabbitMQ;
use PhpAmqpLib\Message\AMQPMessage;

class TestController extends CommonController
{
    public function test()
    {
        #RabbitMQ生产者
        $mqModel = new RabbitMQ();
        $mqModel->setExchange(MainEnum::RabbitMQ['exchange']['消息'])->setRoutingKey(
            MainEnum::RabbitMQ['routingKey']['消息|用户注册成功']
        )->setQueue(MainEnum::RabbitMQ['queue']['消息|用户注册成功'])->setConfirmSelectType(1)->preparePublisher();
        $temp = [];
        for ($i = 1; $i < 200000000; $i++) {
            $temp[] = [
                'nihao',
            ];
            if (is_int($i / 1000)) {
                $mqModel->publisher($temp);
                $temp = [];
                sleep(1);
            }
        }
    }

    public function serverUp()
    {
        #RabbitMQ消费者
        $mqModel           = new RabbitMQ();
        $confirmSelectType = 1;
        $mqModel->setExchange(MainEnum::RabbitMQ['exchange']['消息'])->setRoutingKey(
            MainEnum::RabbitMQ['routingKey']['消息|用户注册成功']
        )->setQueue(MainEnum::RabbitMQ['queue']['消息|用户注册成功'])->setConfirmSelectType(
            $confirmSelectType,
            [
                static function (AMQPMessage $message) {
                    echo 'Message acked with content ' . $message->body . PHP_EOL;
                },
                static function (AMQPMessage $message) {
                    echo 'Message nacked with content ' . $message->body . PHP_EOL;
                },
                static function ($replyCode, $replyText, $exchange, $routingKey, AMQPMessage $message) {
                    echo 'Message returned with content ' . $message->body . PHP_EOL;
                },
            ]
        )->setPrefetchCount(1000);
        $consumerTag = 'No.1';
        $mqModel->consumer(
            $consumerTag,
            static function ($message) {
                $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']);
                if ($message->body === 'quit') {
                    $message->getChannel()->basic_cancel($message->getConsumerTag());
                }
            }
        );
    }
}